(function ($) {
    var osmUrl = 'http://mt2.google.cn/vt/lyrs=y@177000000&hl=zh-CN&gl=cn&z={z}&x={x}&y={y}&s=Galil',
        map, drawnItems;
    var circleIcon = L.divIcon({className: 'my-div-icon'});

    var FIELD_TYPE = {
        '1': '田地',
        '2': '树木',
        '3': '道路',
        '5': '新增点',
        '6': '河流'
    };

    $.uavMap = {
        border: [],
        barrier: [],
        refBorder: [],
        planning: [],
        init: function (opts) {
            var _this = this;
            if (null != map) {
                return {m: map, d: drawnItems};
            }
            map = new L.Map('tab1', {
                layers: [L.tileLayer(osmUrl, {maxZoom: 20})],
                center: new L.LatLng(30.598428, 114.311831),
                zoom: 17,
                doubleClickZoom: false,
                preferCanvas: true
            });
            drawnItems = L.featureGroup().addTo(map);

            map.addControl(new L.control.zoom({position: 'topright'}));
            map.addControl(new L.Control.Draw({
                position: 'topright',
                edit: {
                    featureGroup: drawnItems,
                    poly: {
                        allowIntersection: true
                    }
                },
                draw: {
                    polygon: {
                        allowIntersection: true,
                        showArea: true
                    }
                }
            }));

            return {m: map, d: drawnItems};
        },
        clear: function (obj) {
            var _this = this, map = obj.m, drawnItems = obj.d;
            for (var j = 0; j < this.border.length; j++) {
                map.removeLayer(this.border[j]);
            }
            this.border = [];

            for (var j = 0; j < this.barrier.length; j++) {
                map.removeLayer(this.barrier[j]);
            }
            this.barrier = [];

            for (var j = 0; j < this.planning.length; j++) {
                map.removeLayer(this.planning[j]);
            }
            this.planning = [];
        },
        addBarrierLatLng: function (obj, barrierList) {
            var _this = this, map = obj.m, drawnItems = obj.d;

            if (!barrierList) {
                console.log('障碍物为空')
                return;
            }

            barrierList = barrierList.split('|');

            console.log('--barrierList--', barrierList);

            for (var k = 0; k < barrierList.length; k++) {

                var step = barrierList[k], arr = step.split(";");

                var polygonArr = [];
                for (var j = 0; j < arr.length; j++) {
                    var step = arr[j].split(",");
                    polygonArr.push(step);
                }

                var polygon = L.polygon(polygonArr, {
                    color: 'rgb(51, 136, 255)'
                });

                drawnItems.addLayer(polygon);
                _this.barrier.push(polygon);
            }
        },
        addBorderLatLng: function (obj, polygonArr) {
            var _this = this, map = obj.m, drawnItems = obj.d;

            var polygon = L.polygon(polygonArr, {
                color: '#00b7ee',
                fillColor: '#000',
                fillOpacity: 0.3,
                weight: 1
            });
            drawnItems.addLayer(polygon);
            _this.border.push(polygon);

            var _html = function (lat, lng, fieldType) {
                return ['<h3>边界点</h3>',
                    '<p>经度:', lng, '</p>',
                    '<p>纬度:', lat, '</p>',
                    '<form>类型:', fieldType, '</form>',
                    ''].join('');
            }
            for (var k = 0; k < polygonArr.length; k++) {
                var polygonArrType = FIELD_TYPE[polygonArr[k][2]] || '未知';

                var marker = L.marker(polygonArr[k], {icon: circleIcon})
                    .addTo(map)
                    .bindPopup(_html(polygonArr[k][1], polygonArr[k][0], polygonArrType));

                map.addLayer(marker);
                _this.border.push(marker);
            }
            map.panTo(this.latlngCenter(polygonArr), 17);
        },
        addPlan: function (obj, arr) {
            var _this = this, map = obj.m;

            for (var j = 0; j < _this.planning.length; j++) {
                map.removeLayer(_this.planning[j]);
            }
            _this.planning = [];

            var planningArr = [];
            // var planningArrOn = [];
            // var planningArrOff = [];
            var sprayCtrlFlag = 0;

            for (var i=0; i<arr.length; i++){
                var t = arr[i];
                var _lat = t.lat || 0, _lng = t.lng || 0;

                //console.log(t.sprayCtrl);

                if (i == arr.length - 1) {

                    var color = '';

                    if (t.sprayCtrl == 1) {
                        color = 'yellow';
                    } else {
                        color = '#9f1369';
                    }
                    planningArr.push([Number(_lat), Number(_lng), 1]);
                    var polygon = L.polyline(planningArr, {
                        color: color,
                        //fillColor: '#9f1369',
                        //fillOpacity: 0.2,
                        weight: 1
                    }).addTo(map);
                    _this.planning.push(polygon);
                }

                if (i > 0) {

                    if (t.sprayCtrl != sprayCtrlFlag) {

                        var color = '';

                        if (sprayCtrlFlag == 1) {
                            color = 'yellow';
                        } else {
                            color = '#9f1369';
                        }
                        planningArr.push([Number(_lat), Number(_lng), 1]);

                        var polygon = L.polyline(planningArr, {
                            color: color,
                            //fillColor: '#9f1369',
                            //fillOpacity: 0.2,
                            weight: 1
                        }).addTo(map);

                        //_this.planning = [];
                        _this.planning.push(polygon);

                        map.panTo(this.latlngCenter(planningArr), 17);

                        //var prev = planningArr[planningArr.length-1];
                        planningArr = [];
                        //planningArr.push(prev);
                        planningArr.push([Number(_lat), Number(_lng), 1]);
                    } else {
                        planningArr.push([Number(_lat), Number(_lng), 1]);
                    }
                    sprayCtrlFlag = t.sprayCtrl;
                } else {
                    planningArr.push([Number(_lat), Number(_lng), 1]);
                    sprayCtrlFlag = t.sprayCtrl;
                }
                // if (t.sprayCtrl == 1) {
                //     planningArrOn.push([Number(_lat), Number(_lng), 1]);
                // } else {
                //     planningArrOff.push([Number(_lat), Number(_lng), 1]);
                // }
                //planningArr.push([Number(_lat), Number(_lng), 1]);
            }


            /*
            var polygonOn = L.polyline(planningArrOn, {
                color: '#eaf806',
                fillColor: '#9f1369',
                fillOpacity: 0.2,
                weight: 1
            }).addTo(map);

            _this.planning.push(polygonOn);

            map.panTo(this.latlngCenter(planningArrOn), 17);

            var polygonOff = L.polyline(planningArrOff, {
                color: '#14f476',
                fillColor: '#9f1369',
                fillOpacity: 0.2,
                weight: 1
            }).addTo(map);

            _this.planning.push(polygonOff);

            map.panTo(this.latlngCenter(planningArrOff), 17);

            */


            /*
                        var polygon = L.polyline(planningArr, {
                            color: '#9f1369',
                            fillColor: '#9f1369',
                            // color: '#9f1369',
                            // fillColor: '#9f1369',
                            fillOpacity: 0.2,
                            weight: 1
                        }).addTo(map);

                        _this.planning.push(polygon);

                        map.panTo(this.latlngCenter(planningArr), 17);
            */
        },
        addRefBorder: function (obj, opts) {
            var _this = this, map = obj.m, drawnItems = obj.d;
            var firstKey = opts.firstKey,
                settingsRefBorderStr = opts.settingsRefBorderStr,
                borderArr = opts.borderArr;

            for (var j = 0; j < this.refBorder.length; j++) {
                map.removeLayer(this.refBorder[j]);
            }

            var refBorderLayer;
            if (firstKey == 'settings' && settingsRefBorderStr) {
                var s = settingsRefBorderStr.split(';');
                var p1 = s[0].split(','), p2 = s[1].split(',');
                refBorderLayer = L.polyline([[p1[0], p1[1]], [p2[0], p2[1]]], {
                    weight: 2,
                    index: 1,
                    color: '#F00'
                }).addTo(map);
            }
            else {
                var pArr = firstKey.split('_');

                if ( !isNaN(pArr[0]) &&  !isNaN(pArr[1])){
                    var end = pArr[1] >= borderArr.length ? 0 : pArr[1];
                    refBorderLayer = L.polyline([borderArr[pArr[0]], borderArr[end]], {
                        weight: 2,
                        index: 1,
                        color: '#F00'
                    }).addTo(map);
                }
            }

            this.refBorder = [];
            if (refBorderLayer)  {
                this.refBorder.push(refBorderLayer);
            }
        },
        switchTab: function (obj, opts) {
            var borderStr = opts.border_list,
                barrierArr = opts.barrier_list,
                refBorderStr = opts.ref_border,
                problemList = opts.problem_list;

            var arr = borderStr.split(";");
            var polygonArr = [];
            for (var j = 0; j < arr.length; j++) {
                var _sub = arr[j].split(',');
                polygonArr.push([Number(_sub[0]), Number(_sub[1]), 1]);
            }
            this.addRefBorder(obj, {
                firstKey: opts.currentLabel,
                settingsRefBorderStr: refBorderStr,
                borderArr: polygonArr
            });
            var firstError = problemList[opts.currentLabel];

            if(firstError.planning_point_list) {
                this.addPlanNew(obj,firstError.planning_point_list)
                /*
                $.get("/tsui/getPlannintPointList", {
                    id: firstError.planning_point_list
                }, function (data) {
                    if (data && data.code == '000000') {
                        // var temp = (data && data.result) || {};

                        var l = (data && data.result) || {};

                        console.log('llllllllllllll'+l);
                        if (l != {}) {
                            $.uavMap.addPlan(obj, l);
                        }
                    } else {
                        return ;
                    }
                });
                */

                 // this.addPlan(obj, firstError.planning_point_list);
            }
        },
        render: function (obj, opts) {
            var _this = this, map = obj.m, drawnItems = obj.d;

            this.clear(obj);

            var borderStr = opts.border_list,
                barrierArr = opts.barrier_list,
                refBorderStr = opts.ref_border,
                problemList = opts.problem_list;

            var arr = borderStr.split(";");
            var polygonArr = [];
            for (var j = 0; j < arr.length; j++) {
                var _sub = arr[j].split(',');
                polygonArr.push([Number(_sub[0]), Number(_sub[1]), 1]);
            }
            this.addBorderLatLng(obj, polygonArr);

            this.addBarrierLatLng(obj, barrierArr);

            var firstKey = opts.calc_ref_border ? opts.calc_ref_border : Object.keys(problemList)[0];
            this.addRefBorder(obj, {
                firstKey: firstKey,
                settingsRefBorderStr: refBorderStr,
                borderArr: polygonArr
            });
            var firstError = problemList[firstKey];
            if(firstError.planning_point_list) {
                //this.addPlan(obj, firstError.planning_point_list);
                this.addPlanNew(obj,firstError.planning_point_list)
                /*
                $.get("/tsui/getPlannintPointList", {
                    id: firstError.planning_point_list
                }, function (data) {
                    if (data && data.code == '000000') {

                        var l = (data && data.result) || {};

                        console.log('llllllllllllll'+l);
                        if (l != {}) {
                            $.uavMap.addPlan(obj, l);
                        }
                    } else {
                        return ;
                    }
                });
                */
            }
        },
        addPlanNew:function(o,id){
            $.get("/tsui/getPlannintPointList", {
                id: id
            }, function (data) {
                if (data && data.code == '000000') {

                    var l = (data && data.result) || {};
                    if (l != {}) {
                        $.uavMap.addPlan(o, l);
                    }
                } else {
                    return ;
                }
            });
        },
        latlngCenter: function (latlngarr) {
            var total = latlngarr.length;
            var X = 0, Y = 0, Z = 0;
            var center = [];
            $.each(latlngarr, function (index, lnglat) {
                var lng = lnglat[1] * Math.PI / 180;
                var lat = lnglat[0] * Math.PI / 180;
                var x, y, z;
                x = Math.cos(lat) * Math.cos(lng);
                y = Math.cos(lat) * Math.sin(lng);
                z = Math.sin(lat);
                X += x;
                Y += y;
                Z += z;
            });

            X = X / total;
            Y = Y / total;
            Z = Z / total;

            var Lng = Math.atan2(Y, X);
            var Hyp = Math.sqrt(X * X + Y * Y);
            var Lat = Math.atan2(Z, Hyp);
            center = [Lat * 180 / Math.PI, Lng * 180 / Math.PI];
            return center;
        }
    };

})(jQuery);